from PIL import Image
from eagleocr.split import imgDispose
from eagleocr.split import wordsToImg
from eagleocr.lib import colorChange


def get_img_2v(img_path=None, img=None):
    '''
    获取二值图像
    参数：
        img_path： 图片路径
    返回：
        img: 二值图片
        sf: 全局系数
    '''
    if img_path:
        nimg = Image.open(img_path)
    else:
        nimg = img
    img_2v, sf = imgDispose.get_2v_img(nimg)
    img_2v.save('aaa.png')
    return img_2v, sf


def save_hyaline_img_2v(img_2v, filename):
    '''
    把文字切割的中间图保存成一张透明图
    参数:
        img_2v: img_2v
        save_folder: /dasd
        name: test
    返回:
        str: filename
    '''
    img_2v_hyaline = colorChange.hyaline(img_2v)
    img_2v_hyaline.save(filename)
    return filename


def save_words_img(img_2v_path, sf, save_folder, hyaline=True):
    '''
    把图片中的文字保存成图片
    参数:
        img_2v: 二值图片
        sf: 全局系数
        trans: True/False(是否旋转图片(顺时针90度))
        hyaline: True/False(是否保存成透明图)
    返回:
        字典(各个字的编号及name)
    '''
    img_2v = Image.open(img_2v_path)
    img_2v = img_2v.transpose(Image.ROTATE_90)
    wnames = wordsToImg.words_2_img(
        img_2v, sf, hyaline=hyaline)
    for k, v in wnames.items():
        img = v['img']
        name = v['name']
        img = img.transpose(Image.ROTATE_270)
        img.save('{0}{1}'.format(save_folder, name))
        v.pop('img')
    return wnames
